//
//  YCContants.swift
//  YCSwiftTest
//
//  Created by Billy on 2024/9/25.
//

import UIKit
import Foundation

/// 当前 App 的主窗口（Key Window），兼容 iOS 13～17
public var AppWindow: UIWindow? {
    if #available(iOS 15.0, *) {
        return UIApplication.shared
            .connectedScenes
            .compactMap { $0 as? UIWindowScene }
            .flatMap { $0.windows }
            .first(where: { $0.isKeyWindow })
    } else {
        // iOS 13–14：使用未废弃的 windows API
        return UIApplication.shared.windows.first(where: { $0.isKeyWindow })
    }
}

public let ScreenWidth = UIScreen.main.bounds.width

public let ScreenHeight = UIScreen.main.bounds.height

/// iOS13 状态栏高度获取方式
public let StatusHeight = TopSafeHeight

public let edgeZero: UIEdgeInsets = .zero

/// iOS11+ 是否存在安全区（如 iPhone X 及以上）
public var safeAreaExist: Bool {
    guard #available(iOS 11.0, *) else { return false }

    let keyWindow: UIWindow? = {
        if #available(iOS 15.0, *) {
            // iOS 15 及以上推荐写法
            return UIApplication.shared
                .connectedScenes
                .compactMap { $0 as? UIWindowScene }
                .flatMap { $0.windows }
                .first(where: { $0.isKeyWindow })
        } else {
            // iOS 13~14 写法
            return UIApplication.shared.windows.first(where: { $0.isKeyWindow })
        }
    }()
    
    return keyWindow?.safeAreaInsets != .zero
}

/// 顶部安全区高度
public var TopSafeHeight: CGFloat {
    return AppWindow?.safeAreaInsets.top ?? 20
}

/// 底部安全区高度
public var BottomSafeHeight: CGFloat {
    return AppWindow?.safeAreaInsets.bottom ?? 0
}

/// tabbar高度
public let TabbarHeight: CGFloat = UIDevice.current.isIPhoneXMore() ? 83: 49

/// 导航条高度
public let NaviBarHeight = 44

/// 导航栏高度
public let NavigationHeight = StatusHeight  + 44

// 自定义标题的高度
public let NavTitleHeight = StatusHeight + 11

extension UIDevice {
    
    /// 判断是否是全面屏设备（如 iPhone X 及之后的机型）
    public func isIPhoneXMore() -> Bool {
        guard #available(iOS 11.0, *) else { return false }

        let keyWindow: UIWindow? = {
            if #available(iOS 15.0, *) {
                return UIApplication.shared
                    .connectedScenes
                    .compactMap { $0 as? UIWindowScene }
                    .flatMap { $0.windows }
                    .first(where: { $0.isKeyWindow })
            } else {
                return UIApplication.shared.windows.first(where: { $0.isKeyWindow })
            }
        }()
        
        return keyWindow?.safeAreaInsets.bottom ?? 0 > 0
    }
}


